package com.artron.mediaartron.ui.widget;

import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-07-25.
 */

public class DrawableTextViewWrapper implements View.OnTouchListener {

    private TextView mTextView;
    private boolean mHasPerformedLongPress = false;

    public DrawableTextViewWrapper(TextView textView) {
        this.mTextView = textView;
        mTextView.setOnTouchListener(this);
    }

    private DrawableRightClickListener mDrawableRightClickListener;
    private static final int DRAWABLE_RIGHT = 2;

    public interface DrawableRightClickListener {
        void onDrawableRightClickListener(View view);
    }

    public void setDrawableRightClickListener(DrawableRightClickListener listener) {
        this.mDrawableRightClickListener = listener;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Drawable drawableRight = mTextView.getCompoundDrawables()[DRAWABLE_RIGHT];
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (mDrawableRightClickListener != null) {
                    if (drawableRight != null && event.getRawX() >= (mTextView.getRight() - drawableRight
                            .getBounds()
                            .width())) {
                        mHasPerformedLongPress = false;
                        return true;
                    }
                }
                break;

            case MotionEvent.ACTION_UP:
                if (drawableRight != null && event.getRawX() >= (mTextView.getRight() - drawableRight
                        .getBounds()
                        .width())
                        && !mHasPerformedLongPress) {
                    mDrawableRightClickListener.onDrawableRightClickListener(mTextView);
                    return true;
                }
                mHasPerformedLongPress = true;
                break;
        }
        return false;

    }
}
